package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author Acer
 */
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter {

    private final AuthProperties authProperties;
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
    private final JwtTool jwtTool;

    /****
     * 校验用户身份*/
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        1、获取对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//        2、校验是否访问开放地址
        String uri = request.getPath().toString();
        if (isExclude(uri)){
            return chain.filter(exchange);
        }
//        3、获取请求头令牌
        String token = request.getHeaders().getFirst("authorization");
//        4、检验令牌是否有效
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            //提示参数错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //响应状态码
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON); //响应JSON类型
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"请先登录！\"}".getBytes(StandardCharsets.UTF_8))));
        }
//      5、获取用户id ， 并封装到请求头
        String userInfo = userId.toString();
        exchange.mutate().request(builder -> builder.header("user-info",userInfo));
        return chain.filter(exchange);
    }


    /****
     * 匹配地址是否需要拦截*/
    public boolean isExclude(String uri){
        return authProperties.getExcludePaths()
                .stream().anyMatch(ep -> ANT_PATH_MATCHER.match(ep, uri));
    }
}
